import { PrismaClient } from '@prisma/client'

// 全局Prisma客户端实例，确保连接池复用
let prisma: PrismaClient

declare global {
  var __prisma: PrismaClient | undefined
}

// 连接池配置
const connectionConfig = {
  // 连接池大小
  connectionLimit: 20,
  // 连接超时时间（毫秒）
  connectionTimeout: 30000,
  // 查询超时时间（毫秒）
  queryTimeout: 60000,
  // 空闲连接超时时间（毫秒）
  idleTimeout: 300000,
  // 最大重试次数
  maxRetries: 3,
  // 重试间隔（毫秒）
  retryDelay: 1000
}

// 创建Prisma客户端实例
function createPrismaClient(): PrismaClient {
  return new PrismaClient({
    datasources: {
      db: {
        url: process.env.DATABASE_URL
      }
    },
    log: process.env.NODE_ENV === 'development' ? ['query', 'error', 'warn'] : ['error'],
    errorFormat: 'pretty'
  })
}

// 获取Prisma客户端实例（单例模式）
export function getPrismaClient(): PrismaClient {
  if (process.env.NODE_ENV === 'production') {
    // 生产环境：使用全局实例
    if (!global.__prisma) {
      global.__prisma = createPrismaClient()
    }
    return global.__prisma
  } else {
    // 开发环境：使用模块级实例
    if (!prisma) {
      prisma = createPrismaClient()
    }
    return prisma
  }
}

// 优雅关闭数据库连接
export async function closePrismaConnection(): Promise<void> {
  const client = getPrismaClient()
  await client.$disconnect()
}

// 健康检查
export async function checkDatabaseHealth(): Promise<boolean> {
  try {
    const client = getPrismaClient()
    await client.$queryRaw`SELECT 1`
    return true
  } catch (error) {
    console.error('Database health check failed:', error)
    return false
  }
}

// 连接池监控
export class ConnectionPoolMonitor {
  private static instance: ConnectionPoolMonitor
  private metrics = {
    activeConnections: 0,
    totalQueries: 0,
    failedQueries: 0,
    averageQueryTime: 0,
    lastHealthCheck: new Date()
  }

  static getInstance(): ConnectionPoolMonitor {
    if (!ConnectionPoolMonitor.instance) {
      ConnectionPoolMonitor.instance = new ConnectionPoolMonitor()
    }
    return ConnectionPoolMonitor.instance
  }

  recordQuery(success: boolean, duration: number): void {
    this.metrics.totalQueries++
    if (!success) {
      this.metrics.failedQueries++
    }
    
    // 计算平均查询时间
    this.metrics.averageQueryTime = 
      (this.metrics.averageQueryTime * (this.metrics.totalQueries - 1) + duration) / 
      this.metrics.totalQueries
  }

  getMetrics() {
    return { ...this.metrics }
  }

  async performHealthCheck(): Promise<boolean> {
    const start = Date.now()
    const healthy = await checkDatabaseHealth()
    const duration = Date.now() - start
    
    this.recordQuery(healthy, duration)
    this.metrics.lastHealthCheck = new Date()
    
    return healthy
  }
}

export { connectionConfig }
